package com.djhu.freepartner.web.control;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.djhu.freepartner.bean.PartnerLoginRecord;
import com.djhu.freepartner.bean.PartnerUser;
import com.djhu.freepartner.core.RestRsp;
import com.djhu.freepartner.core.Status;
import com.djhu.freepartner.core.exception.ServiceException;
import com.djhu.freepartner.service.IPartnerLoginRecordService;
import com.djhu.freepartner.service.IPartnerUserService;
import com.djhu.freepartner.utils.DateUtils;
import com.djhu.freepartner.web.control.manager.SessionManager;
import com.djhu.freepartner.web.support.HttpKit;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;

@RestController
@Api("用户登录相关的接口")
@RequestMapping("/")
public class LoginControl {


    @Autowired
    private IPartnerUserService userService;

    @Autowired
    private IPartnerLoginRecordService recordService;

    @Autowired
    private ExecutorService executorService;

    @ApiOperation(value="用户登录", notes="登录接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "user", value = "用户实体user", required = true, dataType = "PartnerUser")
    })
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public RestRsp login(@RequestBody PartnerUser user) throws ServiceException {


        Wrapper<PartnerUser> wapper = new EntityWrapper<PartnerUser>().eq("username",user.getUsername());
        PartnerUser partnerUser =  userService.selectOne(wapper);
        if (partnerUser == null){
            //用户不存在
            throw new ServiceException(Status.ACCOUNT_NOT_FOUND);
        }
        String password = user.getPassword();
        if (!DigestUtils.md5DigestAsHex(DigestUtils.md5DigestAsHex(password.getBytes()).getBytes()).equals(partnerUser.getPassword())){
            throw new ServiceException(Status.LOGIN_FAILD);
        }

        //用户被禁用 》？？


        //清除之前用户的缓存
        PartnerUser userInfo = SessionManager.me().addPartnerUserToSession(partnerUser);


        //记录登录日志
        PartnerLoginRecord partnerLoginRecord = buildPartnerLoginRecord(userInfo,"login");
        recordService.insert(partnerLoginRecord);
//        executorService.execute(() -> {
//            PartnerLoginRecord partnerLoginRecord = buildPartnerLoginRecord(userInfo,"login");
//            recordService.insert(partnerLoginRecord);
//        });

        RestRsp restRsp = new RestRsp();
        restRsp.setCode(0);
        Map<String,Object> retInfo = new HashMap<>();
        retInfo.put("userid",userInfo.getUserid());
        retInfo.put("username",userInfo.getUsername());
        retInfo.put("sessionid",userInfo.getSessionid());
        restRsp.setData(retInfo);
        return restRsp;
    }

    private PartnerLoginRecord buildPartnerLoginRecord(PartnerUser userInfo,String method) {
        PartnerLoginRecord partnerLoginRecord = new PartnerLoginRecord();
        partnerLoginRecord.setIp(HttpKit.getIp());
        partnerLoginRecord.setUseragent(HttpKit.getRequest().getHeader("user-agent"));
        partnerLoginRecord.setOperator(method);
        partnerLoginRecord.setUserid(userInfo.getUserid());
        partnerLoginRecord.setClienttype(HttpKit.getRequest().getHeader("user-agent"));
        partnerLoginRecord.setLogindate(DateUtils.now());
        return partnerLoginRecord;
    }

    @ApiOperation(value="用户退出", notes="用户退出接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "user", value = "用户实体user", required = true, dataType = "PartnerUser")
    })
    public RestRsp logout(@RequestBody PartnerUser user){
        SessionManager.me().deleteSessionByUser(user);
        return null;
    }

}
